package com.ruoyi.demo.controller.app;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.demo.domain.AuctionFavorite;
import com.ruoyi.demo.domain.dto.AuctionFavoriteWithGoodsDTO;
import com.ruoyi.demo.service.IAuctionFavoriteService;
import com.ruoyi.demo.utils.RequestUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "小程序-收藏")
@RestController
@RequestMapping("/app/favorite")
public class AppAuctionFavoriteController extends BaseController {
    @Autowired
    private IAuctionFavoriteService auctionFavoriteService;

    @ApiOperation("查询收藏列表")
    @GetMapping("/list")
    public TableDataInfo list(AuctionFavorite auctionFavorite) {
        startPage();
        List<AuctionFavorite> list = auctionFavoriteService.selectAuctionFavoriteList(auctionFavorite);
        return getDataTable(list);
    }

    @ApiOperation("获取收藏详细信息")
    @GetMapping(value = "/{favoriteId}")
    public AjaxResult getInfo(@PathVariable("favoriteId") Long favoriteId) {
        return success(auctionFavoriteService.selectAuctionFavoriteByFavoriteId(favoriteId));
    }

    @ApiOperation("新增收藏")
    @PostMapping
    public AjaxResult add(@RequestBody AuctionFavorite auctionFavorite) {
        return toAjax(auctionFavoriteService.insertAuctionFavorite(auctionFavorite));
    }

    @ApiOperation("删除收藏")
    public AjaxResult remove(@PathVariable Long[] favoriteIds) {
        return toAjax(auctionFavoriteService.deleteAuctionFavoriteByFavoriteIds(favoriteIds));
    }

    @ApiOperation("根据token获取用户收藏列表")
    @GetMapping("/myFavorites")
    public TableDataInfo myFavorites() {
        // 使用RequestUtils工具类获取当前登录用户ID
        Long userId = RequestUtils.getCurrentUserId();
        startPage();
        List<AuctionFavoriteWithGoodsDTO> list = auctionFavoriteService.selectFavoriteWithGoodsByUserId(userId);
        return getDataTable(list);
    }

    @ApiOperation("查询商品是否被当前用户收藏")
    @GetMapping("/check/{goodsId}")
    public AjaxResult checkFavorite(@PathVariable("goodsId") @ApiParam("商品ID") Long goodsId) {
        // 获取当前登录用户ID
        Long userId = RequestUtils.getCurrentUserId();
        if (userId == null) {
            return AjaxResult.error(401, "请先登录");
        }

        boolean isFavorite = auctionFavoriteService.isFavorite(userId, goodsId);
        Map<String, Boolean> data = new HashMap<>();
        data.put("isFavorite", isFavorite);
        return AjaxResult.success(data);
    }
}
